package com.catsic.web.controllers;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.WebAttributes;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.catsic.base.annotation.Log;
import com.catsic.base.controller.BaseController;
import com.catsic.base.exception.CatsicException;
import com.catsic.core.UserInfo;
import com.catsic.core.form.UserForm;
import com.catsic.core.user.service.UserService;
import com.catsic.pub.exception.CatsicExceptionCode;

@Controller
public class LoginController extends BaseController {

	@Autowired
	private UserService userService;

	/**
	 * loginSuccess:异步ajax请求，登录成功后，转向的URL
	 * 多使用于登录方式为异步请求成功后，前端自行跳转至首页面(如：手机端原生app)
	 * @author yangyd
	 * @return
	 */
	@RequestMapping(value="/loginSuccess")
	@ResponseBody
	@Log(module = "系统管理", operation = "登录")
	public Map<String,Object> loginSuccess(){
		UserInfo userInfo = (UserInfo)getCurrentUser();
		UserForm userForm = userService.findUserById(userInfo.getUserId());
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("user", userForm);
		map.put("result", RESULT_SUCCESS);
		return map;
	}
	
	/**
	 * loginFailure:异步ajax请求，登录失败后，转向的URL
	 * 多使用于登录方式为异步请求失败后，前端进行提示具体错误(如：手机端原生app)
	 * @author yangyd
	 * @return
	 */
	@RequestMapping(value="/loginFailure")
	@ResponseBody
	public Map<String,Object> loginFailure(){
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(); 
		Exception exception = (Exception) request.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("result", RESULT_FAIL);
		map.put("errorCode", CatsicExceptionCode.登录错误);
		map.put("errorMessage",  exception.getMessage());
		return map;
	}
	
	/**
	 * logoutSuccess:退出登录成功后，转向的URL
	 * 多使用于退出方式为异步请求成功后，前端自行跳转至登录页(如：手机端原生app)
	 * @author yangyd
	 * @return
	 */
	@RequestMapping(value="/logoutSuccess")
	@ResponseBody
	public Map<String,Object> logoutSuccess(){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("result", RESULT_SUCCESS);
		return map;
	}
	
	/**
	 * rememberMe:记住我，原生APP手机端
	 * @author yangyd
	 * @return
	 */
	@RequestMapping(value="/rememberMe")
	@ResponseBody
	public Map<String,Object> rememberMe(){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("result", RESULT_SUCCESS);
		return map;
	}

	/**
	 * denied:权限访问异常处理控制器
	 * @author yangyd
	 * @param
	 */
	@RequestMapping(value = "/denied")
	public void denied() {
		throw new CatsicException(CatsicExceptionCode.无权限_拒绝访问);
	}
}
